package imgshare.service.impl;

import imgshare.common.api.ResultCode;
import imgshare.common.exception.ApiException;
import imgshare.mapper.CollectMapper;
import imgshare.mapper.ImageMapper;
import imgshare.model.Image;
import imgshare.model.vo.ImageCondition;
import imgshare.model.vo.ImageWithSimpleUserInfo;
import imgshare.service.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@CacheConfig(cacheNames = "images")
@Service
public class ImageServiceImpl implements ImageService {

    @Autowired
    private ImageMapper imageMapper;
    @Autowired
    private CollectMapper collectMapper;

    @Override
    public List<Image> getAllImage() {
        return imageMapper.selectAll();
    }

    @Cacheable(key = "#id")
    @Override
    public Image getImageById(int id) {
        return imageMapper.selectByPrimaryKey(id);
    }

    @CachePut(key = "#image.id")
    @Override
    public void update(Image image) {
        int rowChanged = imageMapper.updateByPrimaryKeySelective(image);
        if (rowChanged == 0) {
            throw new ApiException(ResultCode.SQL_ERROR);
        }
    }

    @Override
    public int add(Image image) {
        int rowChanged = imageMapper.insertSelective(image);
        if (rowChanged == 0) {
            throw new ApiException(ResultCode.SQL_ERROR);
        }
        return rowChanged;
    }

    @Override
    public List<Image> findByCondition(ImageCondition condition) {
        return imageMapper.selectByCondition(condition);
    }

    @Override
    public List<Image> findCollectedImages(Integer userId) {
        return collectMapper.selectByCollect(userId);
    }

    @Override
    public List<Image> findMyFollowingUsersPostedImages(Integer userId) {
        return imageMapper.selectMyFollowingUsersPostedImagesBySubjectId(userId);
    }

    @Override
    public List<ImageWithSimpleUserInfo> findWithSimpleUserInfoByCondition(ImageCondition imageCondition) {
        return imageMapper.selectImageWithUserInfoByCondition(imageCondition);
    }
}
